<template>
  <div>
    <Breadcrumb :opt-data="modelOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable ref="multipleTable" v-loading="tableLoading" :table-id="tableId" :table-hdl="tableHdl"
          :rows="metaDataConfigData" :selectable="true" :custom-empty="true" @pageChanged="getModelData"
          @sizeChanged="getModelData" @filterChange="getModelData"
          @selectionChange="(data) => (this.selectModelData = data)">
          <div slot="customOpts">
            <div class="display-inline">
              <span>已选择 </span>
              <span class="font-color-primary">{{
                selectModelData.length
              }}</span>
              <span> 条</span>
            </div>
          </div>
          <EmptyContent slot="empty" :opt-data="modelOptData"></EmptyContent>
        </EZTable>
      </div>
      <MetadataForm @refresh="getModelData" :metaDataForms="metaDataForm" :isCheckMeta="isCheckMeta"
        :showModelDialog="showModelDialog" :status="status" @closeDialog="closeDialog"></MetadataForm>
      <el-dialog :visible.sync="showUploadDialog"  :close-on-click-modal="false" :append-to-body="true" title="导入设备元数据" width="550px" top="100px"
        class="showUploadDialog">
        <el-upload action="" :before-upload="uploadRoomConfig" accept=".json" drag class="display-inline-block mar-lft-5">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
import { msgCode } from "@/config/string";
import { tableIdConfig, tableOptBtnConfig } from "@/config/table";
import { confirmHandle, deepCopyWithJson, messageHandle, JSONParse } from "@/utils";
import {
  assembleTableOptBtn,
  getTableConfig,
  TableStateHdl,
} from "@/modules/routeParamStateHdl";
import modelTableCfg from "@/config/table/metadataSetting";
import EZTable from "@/components/table/EZTable";
import MetadataForm from "./MetadataForm.vue";
import { _ } from 'vue-underscore';
import { momentFormat } from "@/config/common";
const FileSaver = require('file-saver');
export default {
  name: "MetadataSetting",
  components: {
    EZTable,
    MetadataForm,
  },
  data() {
    return {
      tableLoading: true,
      tableId: tableIdConfig.model,
      tableHdl: null,
      modelData: [],
      showModelDialog: false,
      modelFormLoading: false,
      deviceTypeData: [],
      manufacturerData: [],
      seriesData: [],
      isEditModel: false,
      selectModelData: [],
      metaDataForm: {},
      dialogTitle: '新增元数据',
      isCheckMeta: false,
      metaDataConfigData: [],
      status: 'add',
      showUploadDialog: false,
      allMetaData: [],
      key: Math.random(100) * 100
    };
  },
  computed: {
    modelOptData() {
      return [
        {
          type: 'btn',
          label: '导入设备元数据',
          icon: 'icon-bendidaoru',
          callback: () => {
            this.importData();
          }
        },
        {
          type: 'btn',
          label: '导出设备元数据',
          icon: 'icon-zujiantubiao-daochu',
          callback: () => {
            this.exportData();
          }
        },
        {
          type: "btn",
          label: "新增元数据配置",
          icon: "icon-tianjia",
          callback: () => {
            this.clickCreateBtn();
          },
        },
      ];
    },
  },
  activated() {
    this.initTableConfig();
    this.getModelData();
  },
  methods: {
    initTableConfig() {
      if (this.tableHdl) return;
      const { columns = [], filters = [] } = getTableConfig(
        this.tableId,
        modelTableCfg
      );
      assembleTableOptBtn(columns, ({ type = "", data = {} }) => {
        if (!type) return;
        const model = deepCopyWithJson(data);
        switch (type) {
          case tableOptBtnConfig.edit.type:
            this.isCheckMeta = false
            this.editMetadata(data)
            this.status = 'edit';
            break;
          case tableOptBtnConfig.copy.type:
            this.isCheckMeta = false
            this.copyData(data)
            this.status = 'copy';
            break;
          case tableOptBtnConfig.delete.type:
            this.dialogTitle = '删除元数据';
            this.deleteModel(model);
            break;
          default:
            break;
        }
      });
      this.tableHdl = new TableStateHdl(
        this.$route.name,
        this.tableId,
        columns,
        filters
      );
    },
    //复制数据
    copyData(row) {
      this.showModelDialog = true;
      const { ops = [], valueList = [] } = row;
      const opsValue = _.pluck(ops, 'value');
      let valueData = valueList;
      if (opsValue.includes('range') || opsValue.includes('outside')) {
        valueData = valueList.map(v => {
          const values = v.value.split(',') || [];
          return { ...v, value: values[0], endValue: values[1] };
        });
      }
      this.metaDataForm = {
        ...deepCopyWithJson(row),
        valueList: valueData,
        ops: opsValue,
        // payloadDemo: JSON.stringify(row.payloadDemo, null, 4) || '',
        _id: '',
        ver:''
      };
    },
    //编辑元数据
    editMetadata(row) {
      this.showModelDialog = true;
      const { ops = [], valueList = [] } = row;
      const opsValue = _.pluck(ops, 'value');
      let valueData = valueList;
      if (opsValue.includes('range') || opsValue.includes('outside')) {
        valueData = valueList.map(v => {
          const values = v.value.split(',') || [];
          return { ...v, value: values[0], endValue: values[1] };
        });
      }
      this.metaDataForm = {
        ...deepCopyWithJson(row),
        valueList: valueData,
        ops: opsValue,
        //payloadDemo: JSON.stringify(row.payloadDemo, null, 4) || ''
      };
    },
    //导入数据
    importData() {
      this.showUploadDialog = true
    },
    //导入配置
    uploadRoomConfig(file) {
      let fileReader = new FileReader();
      this.tableLoading = true
      fileReader.onload = async (e) => {
        try {
          const configs = JSONParse(e.target.result || "[]");
          API.metadataSetting
            .alarmMetadata(configs)
            .then(() => {
              this.$message({
                message: "设备元数据导入成功!",
                type: "success",
                duration: 1500,
              });
              this.showUploadDialog = false
              this.getModelData();
            })
            .catch((err) => {
              this.tableLoading = false
              this.showUploadDialog = false
              console.log("err: ", err);
            });
        } catch (err) {
          console.log(`设备元数据导入失败: ${err.message}`);
        }
      };
      fileReader.readAsText(file);
      return false;
    },
    exportData() {
      const param = this.selectModelData.length ? { _id: { $in: _.map(this.selectModelData, '_id') } } : {};
      const labelText = this.selectModelData.length > 0 ? `导出${this.selectModelData.length}条数据` : '导出全部数据'
      confirmHandle({ label: `是否确定要${labelText} ？` }).then(() => {
        this.tableLoading = true
        const ts = moment().format(momentFormat.dateTimeDetailFlat);
        API.metadataSetting.alarmMetaExport({ selector: param }).then(result => {
          const metaTypeBlob = new Blob([JSON.stringify(result.data)], { type: "application/json" });
          FileSaver.saveAs(metaTypeBlob, `设备元数据${ts}.json`);
          this.tableLoading = false
        }).catch(err => {
          this.tableLoading = false
          console.log('err', err)
        });
      }).catch((err) => {
        console.log('##### err #####', err);
      });
    },
    //新增元数据
    clickCreateBtn() {
      this.isCheckMeta = false
      this.status = 'add';
      this.showModelDialog = true;
      this.metaDataForm = {
        category: "",
        brand: "",
        keyName: "",
        dataKey: "",
        keyExp: "",
        dataType: "string",
        isActive: "Y",
        ops: [],
        params: [],
        valueList: [],
        remark: "",
        payloadDemo: "",
        storeKey: ""
      };
    },

    getModelData() {
      this.tableLoading = true;
      this.metaDataConfigData = [];
      const tableParam = this.tableHdl.assembleTableParam();
      API.metadataSetting.alarmMetaList(tableParam).then(resp => {
        this.tableLoading = false;
        const { data = [], total = 0 } = resp || {};
        this.metaDataConfigData = data.map(function (item) {
          const { valueList = [], ops = [] } = item;
          return {
            ...item,
            valueList: valueList,
            params: item.params || [],
            categoryName: item.categoryName,
            brandName: item.brandName,
            opsContent: _.pluck(ops, 'name').join('、'),
            valueContent: _.pluck(valueList, 'name').join('、')
          };
        });
        this.tableHdl.total = total || 0;
      }).catch(err => {
        this.tableLoading = false;
      });
    },

    getAllModelData() {

      const tableParam = this.tableHdl.assembleTableParam();
      API.metadataSetting.alarmMetaList({ pageNo: 1, pageSize: 1000 }).then(resp => {
        this.tableLoading = false;
        const { data = [], total = 0 } = resp || {};
        this.allMetaData = data.map(function (item) {
          const { valueList = [], ops = [] } = item;
          return {
            ...item,
            valueList: valueList,
            params: item.params || [],
            categoryName: item.categoryName,
            brandName: item.brandName,
            opsContent: _.pluck(ops, 'name').join('、'),
            valueContent: _.pluck(valueList, 'name').join('、')
          };
        });
        this.tableHdl.total = total || 0;
      }).catch(err => {
        this.tableLoading = false;
      });
    },
    closeDialog(val) {
      this.showModelDialog = val
      this.status = ''
    },
    deleteModel(model = {}) {
      confirmHandle({ label: `确定要删除检测项：${model.keyName} 吗?` })
        .then(() => {
          this.selectModelData = this.selectModelData.filter(item => item._id !== model._id)
          this.$refs.multipleTable.clearSelection();
          API.metadataSetting.alarmMetaDelete({ _id: model._id }).then((result) => {
            messageHandle({ code: msgCode.DELETE_SUCCESS, title: "设备元数据" });
            this.tableHdl.judgeTableMatched();
            this.getModelData();
          });

        })
        .catch(() => {
        });
    },
  },
};
</script>

<style scoped lang="less">
.showUploadDialog /deep/ .el-dialog__body {
  text-align: center !important;
}
</style>
